/**
 * This file is a part of qloudgen-sec. 
 * You can redistribute qloudgen-sec and/or modify it under the terms of the Lesser GNU General Public License version 3. 
 * qloudgen-sec is distributed WITHOUT ANY WARRANTY. 
 *
 * See the Lesser GNU General Public License for more details at http://www.gnu.org/licenses/. 
 **/
package org.qloudgen.sec.cas.client.filter;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.pac4j.core.client.Client;
import io.buji.pac4j.ShiroWebContext;

import org.apache.shiro.web.filter.PathMatchingFilter;
import org.apache.shiro.web.util.WebUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.qloudgen.sec.util.ExceptionUtil;

/**
 * <p>Title: Cas client proxy receptor Implementation</p>
 * <p>Description: Wrappered cas pgt callback filter with buji-pac4j support.</p>
 * <p>Copyright: qloudgen/sec 2014</p>
 * @author <a href="mailto:hyq.dd.sun@gmail.com">glue.3M</a>
 */
@SuppressWarnings( { "serial" , "unchecked" } )
public class ProxyFilter extends PathMatchingFilter {
	/**
	 * Log output.
	 */
	private final static Logger logger = LoggerFactory.getLogger( ProxyFilter.class );
	/**
	 * Default will broke filter chain.
	 */
	private boolean continueChain = true;
	/**
	 * Default proxy receptor.
	 */
	private Client client = null;
	
	/**
	 * Default constructor.
	 */
	public ProxyFilter() {
	}
	
	/**
	 * Sets current continue chain.
	 *
	 * @param continueChain
	 */
	public void setContinueChain(boolean continueChain) {
		this.continueChain = continueChain;
	}
	
	/**
	 * Returns current continue chain.
	 *
	 * @return boolean
	 */
	public boolean getContinueChain() {
		return continueChain;
	}
	
	/**
	 * Sets current client.
	 *
	 * @param client
	 */
	public void setClient(Client client) {
		this.client = client;
	}
	
	/**
	 * Returns current client.
	 *
	 * @return Client
	 */
	public Client getClient() {
		return client;
	}

	/**
	 * Receive cas proxy granting ticket.
	 *
	 * @param request
	 * @param response
	 * @param mappedValue
	 * @return boolean
	 * @throws Exception
	 */
	@Override
	protected boolean onPreHandle(ServletRequest request , ServletResponse response , Object mappedValue) throws Exception {
		//
		logger.debug( "Current path-config is...{}" , mappedValue );
		logger.debug( "Current client is...{}" , client );
		//
		if ( client == null ) {
			throw new RuntimeException( "Current proxy receptor is null..." );
		}
		//
		try {
			client.getCredentials( new ShiroWebContext( WebUtils.toHttp( request ) , WebUtils.toHttp( response ) ) );
		}
		catch (Exception e) {
			logger.warn( ExceptionUtil.get( e ) );
		}
		/**
		 *
		 */
		return continueChain;
	}
}